import requests
import re
import json
import random
import urllib3
##cron: 59 17 * * *
##new Env("资料最终版")

# 禁用SSL警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# 请求配置
url = "https://d-fjp-461234-dhc.fitzwaterengineering.com:1267/yjjy/amcj/dbyg.js"
cookies = {
    "UM_distinctid": "1965dbf35637d-069707f4db2e0d-3e754f63-735cd-1965dbf356421c",
    "Hm_tf_gyvo5the8wn": "1745329534",
    "Hm_lvt_gyvo5the8wn": "1745329534",
    "CNZZDATA1281288363": "712992130-1745329534-https%253A%252F%252F461234.com%252F%7C1745666419",
    "Hm_lpvt_gyvo5the8wn": "1745666419",
}
headers = {
    "Host": "d-fjp-461234-dhc.fitzwaterengineering.com:1267",
    "Connection": "keep-alive",
    "User-Agent": "Mozilla/5.0 (Linux; Android 14; 23127PN0CC Build/UKQ1.230804.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/131.0.6778.200 Mobile Safari/537.36",
    "Accept": "*/*",
    "Sec-Fetch-Site": "same-origin",
    "Sec-Fetch-Mode": "no-cors",
    "Sec-Fetch-Dest": "script",
    "Referer": "https://d-fjp-461234-dhc.fitzwaterengineering.com:1267/yjjy/main.html",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
}
# 企业微信机器人Webhook
wx_webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c4ed66c7-ea68-4b51-be3f-8319beb4504d"

def send_to_wechat(content):
    """发送消息到企业微信机器人"""
    headers = {"Content-Type": "application/json"}
    data = {
        "msgtype": "text",
        "text": {
            "content": content
        }
    }
    try:
        response = requests.post(wx_webhook, headers=headers, data=json.dumps(data), verify=False)
        if response.status_code == 200:
            print("消息成功推送到企业微信")
        else:
            print(f"消息推送失败: {response.status_code}, {response.text}")
    except Exception as e:
        print(f"推送消息到企业微信时出错: {str(e)}")

def generate_random_numbers():
    """生成随机三中三号码"""
    # 从1-49中随机选择6个不重复的数字
    numbers = random.sample(range(1, 50), 6)
    # 按升序排序
    numbers.sort()
    
    # 格式化输出
    random_content = "🎲 生成随机三中三 🎲\n"
    random_content += "✨ 推荐号码 ✨\n\n"
    random_content += f"📋 选号: {', '.join(f'{num:02d}' for num in numbers)}\n\n"
    random_content += "💡 温馨提示: 彩票有风险，投注需谨慎\n"
    random_content += "🎯 祝您好运！\n"
    
    return random_content

def get_data_with_retry(max_retries=3):
    """带重试机制的数据获取函数"""
    for attempt in range(max_retries):
        try:
            # 发起请求，禁用SSL验证
            res = requests.get(url, headers=headers, cookies=cookies, timeout=10, verify=False)
            res.raise_for_status()
            return res
            
        except requests.exceptions.SSLError as e:
            print(f"SSL错误 (尝试 {attempt + 1}/{max_retries}): {str(e)}")
            if attempt == max_retries - 1:
                raise e
            continue
            
        except requests.exceptions.RequestException as e:
            print(f"请求错误 (尝试 {attempt + 1}/{max_retries}): {str(e)}")
            if attempt == max_retries - 1:
                raise e
            continue
    
    return None

try:
    # 使用带重试机制的函数获取数据
    res = get_data_with_retry()
    
    # 提取所有document.writeln内容
    raw_text = res.text
    matches = re.findall(r'document\.writeln\("(.*?)"\);', raw_text, flags=re.DOTALL)
    
    # 处理每个匹配项
    results = []
    for match in matches:
        # 清理HTML标签
        clean = re.sub(r'<.*?>', '', match)
        # 替换HTML实体
        clean = clean.replace('&nbsp;', ' ').replace('&amp;', '&')
        # 简化多余空格和换行
        clean = re.sub(r'\s+', ' ', clean).strip()
        if clean:
            results.append(clean)
    
    # 处理数据
    data_output = []
    buffer_line = None
    
    for text in results:
        # 处理期号行
        if "期【四肖八码】" in text:
            # 移除非必要字符
            clean_header = re.sub(r'<.*?>|[ \t\r\n?]+', '', text)
            data_output.append({"header": clean_header, "content": []})
        
        # 处理生肖行
        elif "【" in text:
            # 确保当前有有效的期号行
            if not data_output:
                continue
            
            # 清理文本
            clean_match = re.sub(r'<.*?>|\s+', '', text)
            
            # 当缓存行存在时合并输出
            if buffer_line:
                data_output[-1]["content"].append(f"{buffer_line}{clean_match}")
                buffer_line = None
            else:
                buffer_line = clean_match
    
    # 处理剩余的缓存行
    if buffer_line and data_output:
        data_output[-1]["content"].append(buffer_line)
    
    # 按期号从大到小排序
    data_output.sort(
        key=lambda x: int(re.search(r'(\d{1,3})期', x["header"]).group(1)) if re.search(r'\d+期', x["header"]) else 0,
        reverse=True
    )
    
    # 构建详细消息文本（带表情符号）
    message_content = "🎯【四肖八码】🎯\n"
    message_content += "✨ 最新数据汇总 ✨\n\n"
    
    for i, entry in enumerate(data_output[:6]):  # 最多显示6期
        # 添加期号表情
        period_emoji = "🔥" if i == 0 else "⭐" if i == 1 else "📌"
        message_content += f"{period_emoji} {entry['header']}\n"
        
        for content in entry["content"]:
            # 为每个生肖添加表情符号
            content_with_emoji = content
            animal_emojis = {
                "鼠": "🐭", "牛": "🐮", "虎": "🐯", "兔": "🐰",
                "龙": "🐲", "蛇": "🐍", "马": "🐴", "羊": "🐑",
                "猴": "🐵", "鸡": "🐔", "狗": "🐶", "猪": "🐷"
            }
            
            for animal, emoji in animal_emojis.items():
                content_with_emoji = content_with_emoji.replace(f"【{animal}】", f"【{emoji}{animal}】")
            
            message_content += f"   🎲 {content_with_emoji}\n"
        
        message_content += "\n"  # 期与期间空行
    
    # 添加统计信息
    total_periods = len(data_output[:6])
    message_content += f"📈 统计信息：共显示 {total_periods} 期数据\n"
    message_content += "💫 数据更新完成！\n"
    
    # 打印到控制台
    print("处理结果:")
    print(message_content)
    
    # 推送到企业微信机器人
    send_to_wechat(message_content.strip())
    
    # 生成并发送随机三中三号码
    random_numbers_content = generate_random_numbers()
    print("\n生成随机三中三号码:")
    print(random_numbers_content)
    send_to_wechat(random_numbers_content.strip())
    
except requests.exceptions.RequestException as e:
    error_msg = f"❌ 请求失败: {str(e)}"
    print(error_msg)
    send_to_wechat(error_msg)
    
except Exception as e:
    error_msg = f"⚠️ 处理错误: {str(e)}"
    print(error_msg)
    send_to_wechat(error_msg)